
const connect = require("../model/mysql")
const Md5 = require('md5.js')
let  usercon = { }
usercon.register = (req,res)=>{
        res.render('register.html')
}
usercon.registerPost =async (req,res)=>{
    let { user , password } = req.body  
    let sql = `select * from user where user =?`
    let result  =  await connect(sql,[user])
    if(result.length>0){
            res.json({ 
                code:40001,
                msg:"用户名已被占用"
            })
    }else{ 
        password = new Md5().update(password).digest('hex')
        console.log("密码加密",password);
        let sql =`insert into user(user,password)  value( ?, ?  )`
        let   result =   await connect(sql,[user,password])
       
        console.log(' result.affectedRows', result.affectedRows);
        if(     result.affectedRows == 1 ){
            res.json({ 
                code:20000,
                msg:"恭喜您,注册成功"
            })
        }else{ 
            res.json({ 
                code:40005,
                msg:"注册失败"
            })
        }
    }
}
usercon.login = (req,res)=>{
    res.render('login.html')
}
usercon.loginPost =async (req,res)=>{
    let { user , password } = req.body  
    password = new Md5().update(password).digest('hex')
    let sql = `select * from user where  user=? and  password =? and isdele =0`
    let result   =  await connect(sql,[user , password])

    if(result.length==1){
            req.session.userinfo = { 
                user:result[0].user
            }
            res.json({ 
                code:20000,
                msg:"登录成功"
            })
    }else{ 
        res.json({ 
            code:40004,
            msg:"账号密码错误"
        })
    }
}



usercon.index = (req,res)=>{
        console.log("用户信息",req.session.userinfo);
        res.render("index.html")
}
usercon.classify = (req,res)=>{
       
        res.render("book.html")
}
module.exports = usercon